package com.example.myapp.ADO;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.example.myapp.Model.Defaulticon;
import com.example.myapp.R;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.QueryListener;

public class UpdateAppManager {


    private static final String FILE_PATH = Environment.getExternalStorageDirectory () + "/PYB/";
    private static final String FILE_NAME = FILE_PATH + "pyb.apk";
    private static final int UPDATE_TOKEN = 0x29;
    private static final int INSTALL_TOKEN = 0x31;
    private Context context;
    private String message = "检测到本程序有新版本发布，建议您更新！";
    private String spec = "http://bt.hejiawen.cn:8090/down/dhtjhEWVxOcy";
    private String json1 = "http://10.0.2.2:8080/updateMsg";
    String result;
    private String VersionName;//当前版本名
    private int VersionCode ;//当前版本号
    //  http://192.168.0.107:8080/app-debug.apk
    // 下载应用的对话框
    private Dialog dialog;
    // 下载应用的进度条
    private ProgressBar progressBar;
    private int curProgress;
    private boolean isCancel;
    private Defaulticon defaulticon;
    public UpdateAppManager(Context context) {
        this.context = context;
    }

    private final Handler handler = new Handler () {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TOKEN:
                    progressBar.setProgress (curProgress);
                    break;

                case INSTALL_TOKEN:
                    installApp ();
                    break;
            }
        }
    };


    private void showDownloadDialog() {
        View view = LayoutInflater.from (context).inflate (R.layout.progressbar_main, null);
        progressBar = (ProgressBar) view.findViewById (R.id.progressBar);
        AlertDialog.Builder builder = new AlertDialog.Builder (context);
        builder.setTitle ("软件版本更新");
        builder.setView (view);

        builder.setNegativeButton ("取消", new DialogInterface.OnClickListener () {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss ();
                isCancel = true;
            }
        });
        dialog = builder.create ();
        dialog.show ();
        downloadFile(defaulticon.getApk());

    }


    /**
     * 安装新版本应用
     */
    public void installApp() {
        File appFile = new File (FILE_NAME);


        if (!appFile.exists ()) {
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", appFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
//            intent.setDataAndType (Uri.parse ("file://" + appFile.toString ()), "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
        }
        context. startActivity(intent);




//        // 跳转到新版本应用安装页面
//        Intent intent = new Intent (Intent.ACTION_VIEW);
//        intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType (Uri.parse ("file://" + appFile.toString ()), "application/vnd.android.package-archive");
//        context.startActivity (intent);
//        android.os.Process.killProcess (android.os.Process.myPid ());

    }






    public void downloadFile(BmobFile file){
        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
        File saveFile = new File(FILE_PATH, "pyb.apk");
        file.download(saveFile, new DownloadFileListener() {

            @Override
            public void onStart() {

                Log.w("www", "onStart: 开始下载" );
            }

            @Override
            public void done(String savePath, BmobException e) {
                if(e==null){
                    Log.w("www","下载成功,保存路径:"+savePath);
                    handler.sendEmptyMessage (INSTALL_TOKEN);
                }else{
                    Log.w("www","下载失败："+e.getErrorCode()+","+e.getMessage());
                }
            }

            @Override
            public void onProgress(Integer value, long newworkSpeed) {
                Log.i("bmob","下载进度："+value+","+newworkSpeed);
                curProgress = value;
                handler.sendEmptyMessage (UPDATE_TOKEN);

            }

        });
    }



    public void getAdmiVsionMsg(){
        BmobQuery<Defaulticon> bmobQuery = new BmobQuery<Defaulticon>();
        bmobQuery.getObject("nlS2IIIO", new QueryListener<Defaulticon>() {
            @Override
            public void done(Defaulticon object,BmobException err) {
                if (err == null) {
                    defaulticon=object;
                    Log.w("aaaa", "版本信息查询成功！");
                    try {
                        //获取软件版本号，对应AndroidManifest.xml下android:versionCode
                        VersionCode = context.getPackageManager().
                                getPackageInfo(context.getPackageName(), 0).versionCode;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    try {
                        VersionName = context.getPackageManager().
                                getPackageInfo(context.getPackageName(), 0).versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }

                    Log.w("aaaa", "当前版本为："+VersionName);
                    int IntversionCode;

                    try {
                        IntversionCode = Integer.parseInt(object.getVersionCode());
                        if(IntversionCode>VersionCode){
                            new AlertDialog.Builder (context)
                                    .setTitle ("软件版本更新")
                                    .setMessage (object.getVersionName())
                                    .setPositiveButton ("下载", new DialogInterface.OnClickListener () {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss ();
                                            showDownloadDialog ();
                                        }
                                    }).setNegativeButton ("以后再说", new DialogInterface.OnClickListener () {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss ();
                                }
                            }).create ().show ();
                        }

                        else{
                            Log.w("aaaa", "当前最新版本");

                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }//版本号转为int,再比较

                }
            }
        });

    }




    public void getappVsionMsg(){
        BmobQuery<Defaulticon> bmobQuery = new BmobQuery<Defaulticon>();
        bmobQuery.getObject("nlS2IIIO", new QueryListener<Defaulticon>() {
            @Override
            public void done(Defaulticon object,BmobException err) {
                if (err == null) {
                    defaulticon=object;
                    Log.w("aaaa", "版本信息查询成功！");
                    try {
                        //获取软件版本号，对应AndroidManifest.xml下android:versionCode
                        VersionCode = context.getPackageManager().
                                getPackageInfo(context.getPackageName(), 0).versionCode;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    try {
                        VersionName = context.getPackageManager().
                                getPackageInfo(context.getPackageName(), 0).versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }

                    Log.w("aaaa", "当前版本为："+VersionName);
                    int IntversionCode;

                    try {
                        IntversionCode = Integer.parseInt(object.getVersionCode());
                        if(IntversionCode>VersionCode){
                            new AlertDialog.Builder (context)
                                    .setTitle ("软件版本更新")
                                    .setMessage (object.getVersionName())
                                    .setPositiveButton ("下载", new DialogInterface.OnClickListener () {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss ();
                                            showDownloadDialog ();
                                        }
                                    }).setNegativeButton ("以后再说", new DialogInterface.OnClickListener () {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss ();
                                }
                            }).create ().show ();
                        }

                        else{
                            new AlertDialog.Builder (context)
                                    .setTitle ("已经是最新版本")
                                    .setPositiveButton ("取消", new DialogInterface.OnClickListener () {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss ();

                                        }
                                    }).show ();

                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }//版本号转为int,再比较

                }
            }
        });

    }


}
